# -*- coding=utf-8
# appid 已在配置中移除,请在参数 Bucket 中带上 appid。Bucket 由 BucketName-APPID 组成
# 1. 设置用户配置, 包括 secretId，secretKey 以及 Region
import os
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
from Config import COS_Secret_Id
from Config import COS_Secret_Key
from Config import COS_Region
from Config import Put_File_Path
from Config import COS_Bucket_Name
import sys
import logging

class PutFileToCos:
    def __init__(self):
        self.mFileLists = []  # 所有待上传的文件列表
        
        # COS 相关配置
        logging.basicConfig(level=logging.INFO, stream=sys.stdout)
        secret_id = COS_Secret_Id
        secret_key = COS_Secret_Key
        region = COS_Region
        token = None                # 使用临时密钥需要传入 Token，默认为空，可不填
        scheme = 'https'            # 指定使用 http/https 协议来访问 COS，默认为 https，可不填
        config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=token, Scheme=scheme)
        # 2. 获取客户端对象
        self.client = CosS3Client(config)

    def Process(self):
        if(self.GetBucketInfo() is False):
            print("未查询到存储桶：" + COS_Bucket_Name + ", 上传操作已中止.....")
            return
        
        dir= Put_File_Path
        print("============ 正在读取待上传文件 =================")
        self.RecursiveSearchExcel(dir)
        print("============ 待上传文件读取完毕 =================")
        for file in self.mFileLists:
            self.UploadFile(file)

	# 查询存储桶
    def GetBucketInfo(self):
        hasBucket = False
        response = self.client.list_buckets()
        bucketList = response["Buckets"]['Bucket']
        for bucketItem in bucketList:
            if(bucketItem['Name'] == COS_Bucket_Name):
                hasBucket = True

        return hasBucket

    

    # 递归查找文件
    def RecursiveSearchExcel(self, path):
        for pathdir in os.listdir(path):  # 遍历当前目录
            fullpath = os.path.join(path, pathdir)

            if os.path.isdir(fullpath):
                self.RecursiveSearchExcel(fullpath)
            elif os.path.isfile(fullpath):
                self.mFileLists.append(fullpath)


	# 开始上传文件
    def UploadFile(self,fileName):
        # 默认读取出来的路径分隔符是"/"，但是COS中分隔符是"\"才会自动新建文件夹，需要替换
        fileKey = fileName.replace("./","")
        fileKey = fileKey.replace("\\","/")
        print("正在上传 =>" + fileKey)
        # 使用upload_file上传，支持断点续传
        response = self.client.upload_file(
            # 存储桶名称
            Bucket=COS_Bucket_Name,
            # 文件key 即在存储桶中的路径+文件名称
            Key=fileKey,
            # 本地文件路径
            LocalFilePath=fileName,
            # 是否需要 SDK 计算 Content-MD5，默认关闭，打开后会增加上传耗时
            EnableMD5=False
        )
        print("====>" + fileKey + "上传成功, ETag=" + response['ETag'])
